<template>
  <div>
    <!--    高得地图-->
    <div id="container">
    </div>
    <!--    安全图标-->
    <div class="HomeIndex" @click="toSecurity()">
      <van-image
          width="50px"
          height="50px"
          src="https://img95.699pic.com/element/40106/6770.png_860.png"
      />
    </div>
    <div class="HomeIndex1">
      <!--      当前位置-->
      <div class="HomeIndex11" @click="toStartPoint">
        <van-icon name="down" color="#4EA9CB" style="margin-top: 10px;margin-left: 20px"/>
        <van-cell-group style="margin-left: 39px; margin-top: -31px; height: 10px">
          <van-field v-model="startaddress" placeholder="出发点"/>
        </van-cell-group>
      </div>
      <!--      目的地-->
      <div class="HomeIndex111">
        <van-icon name="location" color="red" style="margin-top: 10px;margin-left: 20px"/>
        <van-cell-group style="margin-left: 39px; margin-top: -32px; height: 10px">
          <van-field v-model="endaddress" placeholder="请选择您的目的地" @click="toEnd"/>
        </van-cell-group>
      </div>
    </div>
    <div class="HomeIndex2">
      <!--    预约时间-->
      <div class="HomeIndex22" @click="findByTime">
        <van-icon name="underway-o"/>
        预约时间
      </div>
      <div class="HomeIndex222" @click="toHelpOne()">
        <van-icon name="friends-o"/>
        代叫车
      </div>
      <div class="HomeIndex2222">
        <van-icon name="logistics"/>
        货运
      </div>
    </div>

    <div>
      <van-popup v-model="time" position="bottom" :style="{height: '50vh'}">
        <van-datetime-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="makeDate"
            type="datetime"
            title="选择完整时间"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirm"
        />

      </van-popup>

    </div>


    <BottomPanel/>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import BottomPanel from "@/views/bottomPanel.vue";
import dayjs from 'dayjs';

export default {
  name: "map-view",
  components: {
    BottomPanel,
  },
  data() {
    return {
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      makeDate: null,
      time: false,
      //出发地
      startaddress: "",
      //出发地经纬度
      startLatitudeAndLongitude: "",
      //目的地
      endaddress: "",
      // 目的地经纬度
      endLatitudeAndLongitude: "",

      flag: false,
      selectedDate: null,
    };
  },
  mounted() {
    this.initAMap();
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  },
  created() {
    this.startLocation();
    this.routeCartTypeTime();
    this.end()
  },
  methods: {
    // 跳转到代叫车
    toHelpOne() {
      if (this.startLatitudeAndLongitude==undefined) {
        this.$router.push({
          path: '/helpCartOne',
          query: {
            startaddress: this.startaddress,
            //出发点经纬度
            startLatitudeAndLongitude: this.position
          }
        })
        return;
      }else{
        this.$router.push({
          path: '/helpCartOne',
          query: {
            startaddress: this.startaddress,
            startLatitudeAndLongitude: this.startLatitudeAndLongitude[0] + "," + this.startLatitudeAndLongitude[1],
          }
        })
      }

    },
    end() {
      this.startaddress = this.$route.query.startaddress;
      this.endaddress = this.$route.query.endaddress;
    },
    routeCartTypeTime() {
      const startaddress = this.$route.query.startaddress;
      const endaddress = this.$route.query.endaddress;
      console.log("出发地：", startaddress);
      console.log("目的地：", endaddress);
    },
    startLocation() {
      this.startLatitudeAndLongitude = this.$route.query.startLatitudeAndLongitude;
      if (this.startLatitudeAndLongitude && this.startLatitudeAndLongitude != '') {
        this.flag = true
      }
      console.log("出发点经纬度：", this.startLatitudeAndLongitude);
    },
    toSecurity() {
      this.$router.push({
        path: '/security_center'
      })
    },
    convertToFormat(dateTime) {
      return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss');
    },
    onConfirm(data) {
      console.log(this.startLatitudeAndLongitude)
      console.log(this.endLatitudeAndLongitude)
      var makeDate = this.convertToFormat(data);
      console.log(makeDate);
      this.$router.push({
        path: '/routeCart',
        query: {
          makeDate: makeDate,
          startLatitudeAndLongitude: this.startLatitudeAndLongitude,
          endLatitudeAndLongitude: this.endLatitudeAndLongitude
        }
      })
    },
    findByTime() {
      this.time = !this.time;
    },
    toStartPoint() {
      this.$router.push({
        path: '/startPoint'
      })
    },
    toEnd() {
      console.log("666", this.position)
      console.log(this.position)
      if (this.startLatitudeAndLongitude==undefined) {
        this.$router.push({
          path: '/endPoint',
          query: {
            //出发点经纬度
            startLatitudeAndLongitude: this.position
          }
        })
        return;
      }else{
        this.$router.push({
          path: '/endPoint',
          query: {
            //出发点经纬度
            startLatitudeAndLongitude: this.startLatitudeAndLongitude[0]+","+this.startLatitudeAndLongitude[1]
          }
        })
      }



    },


    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "9708bfa416d306b9dbaf55ea4e4a25f2",
        // securityJsCode: "581034ba75a04c49e89c726c22d9069d",
      };
      let self = this;
      AMapLoader.load({
        key: "e6effe38515227141202b9fb6749424e", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.Geocoder", "AMap.Marker"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
          .then((AMap) => {
            const map = new AMap.Map("container", {
              // 设置地图容器id
              viewMode: "3D", // 是否为3D地图模式
              zoom: 11, // 初始化地图级别
              center: [116.397428, 39.90923], // 初始化地图中心点位置
            });
            // 逆地址
            var geocoder = new AMap.Geocoder({
              city: "", //城市设为北京，默认：“全国”
            });
            AMap.plugin(
                ["AMap.Geolocation", "AMap.Marker"],
                function () {
                  console.log(self.flag)
                  // 定位
                  if (!self.flag) {
                    var geolocation = new AMap.Geolocation({
                      enableHighAccuracy: true,//是否使用高精度定位，默认:true
                      timeout: 10000,          //超过10秒后停止定位，默认：5s
                      buttonPosition: 'RB',    //定位按钮的停靠位置
                      buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                      zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
                      needAddress: true,      //是否返回地址信息
                      resizeEnable: true
                    });
                    map.addControl(geolocation);
                    geolocation.getCurrentPosition(function (status, result) {
                      if (status === 'complete') {
                        onComplete(result);
                      } else {
                        onError(result)
                      }
                    });
                  }

                  if (self.flag) {
                    console.log("查询出发点经纬度：", self.startLatitudeAndLongitude)
                    // // 逆地理编码获取出发点地址信息
                    var start = self.startLatitudeAndLongitude.split(",").map(item => parseFloat(item));
                    console.log("start:", start)
                    // 寻找开始地址的方法
                    geocoder.getAddress(start, function (status, result) {
                      if (status === 'complete' && result.regeocode) {
                        self.startaddress = result.regeocode.formattedAddress;
                        console.log("出发点地址：", self.startaddress)
                      } else {
                        console.log("获取开始地址失败", result);
                      }
                    });
                    // 定位新的地址
                    const marker = new AMap.Marker();
                    geocoder.getLocation(start, function (status, result) {
                      if (status === 'complete' && result.geocodes.length) {
                        // onComplete(result)
                        var strings = self.startLatitudeAndLongitude.split(",");
                        marker.setPosition(strings[0] + "," + strings[1]);
                        console.log("marker:", strings)
                        // console.log("marker:", result.geocodes[0].location)
                        self.startLatitudeAndLongitude = strings;
                        marker.setPosition(self.startLatitudeAndLongitude);
                        map.add(marker);
                        map.setFitView(marker);
                      }
                    });
                  }
                });

            function onComplete(data) {
              console.log("定位成功!");
              // findalltext.position=data.position;
              self.position = data.position + "";
              console.log(self.position);
              console.log("定位结果:" + data.position);
              // self.startLatitudeAndLongitude=self.position;
              // 逆地理编码获取当前位置地址信息
              var currentLocation = self.position.split(",").map(item => parseFloat(item));
              console.log("当前位置经纬度:", currentLocation)
              // 寻找当前位置地址的方法
              geocoder.getAddress(currentLocation, function (status, result) {
                if (status == 'complete' && result.regeocode) {
                  self.startaddress = result.regeocode.formattedAddress;
                  console.log("当前位置地址：", self.startaddress)
                } else {
                  console.log("获取当前位置地址失败", result);
                }
              });
              console.log("定位类别:" + data.location_type);
              console.log("精度:" + data.accuracy + "米");
              console.log("是否经过偏移:" + data.isConverted);
              // document.getElementById('status').innerHTML='定位成功'
              var str = [];
              str.push('定位结果：' + data.position);
              str.push('定位类别：' + data.location_type);
              if (data.accuracy) {
                str.push('精度：' + data.accuracy + ' 米');
              }//如为IP精确定位结果则没有精度信息
              str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
              // this.position=str;
              // document.getElementById('result').innerHTML = str.join('<br>');
            }

            //解析定位错误信息
            function onError(data) {
              console.log("定位失败!")
              console.log("失败原因排查信息:" + data.message)
              // 定位失败
              // document.getElementById('status').innerHTML='定位失败'
              // document.getElementById('result').innerHTML = '失败原因排查信息:'+data.;message
            }

          })
    },


  },

};
</script>
<style scoped>
#container {
  width: 100%;
  height: 80vh;
}

.HomeIndex {
  width: 50px;
  height: 50px;
  position: fixed;
  top: 70vh;
  margin-left: 10px;
}

.HomeIndex1 {
  width: 100%;
  height: 80px;
  box-shadow: 0px -10px 30px -5px black;
}

.HomeIndex11 {
  width: 100%;
  height: 40px;
}

.HomeIndex111 {
  width: 100%;
  height: 40px;
  border-top: 1px solid #919191;
}

.HomeIndex2 {
  width: 100%;
  height: 50px;
}

.HomeIndex22 {
  margin-top: 5px;
  padding-left: 10px;
  line-height: 40px;
  width: 30%;
  height: 40px;
  display: inline-block;
  border-right: 1px solid #919191;
}

.HomeIndex222 {
  margin-top: 5px;
  padding-left: 20px;
  line-height: 40px;
  width: 30%;
  height: 40px;
  display: inline-block;
  border-right: 1px solid #919191;
}

.HomeIndex2222 {
  margin-top: 5px;
  padding-left: 20px;
  line-height: 40px;
  width: 28%;
  height: 40px;
  display: inline-block;
}
</style>

